package org.example.cdpcrpbackend.controller;

import lombok.RequiredArgsConstructor;
import org.example.cdpcrpbackend.controller.dto.Result;
import org.example.cdpcrpbackend.util.FileTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/img")
@RequiredArgsConstructor
public class ImageController {
    @Value("${custom.file-path}")
    private String filePath;

    /**
     * 图片-上传图片
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String fileName = save(file);
        Map<String, Object> data = new HashMap<>();
        data.put("fileName", fileName);
        return Result.success(data);
    }

    /**
     * 图片-响应服务器上的图片
     *
     * @param filename 图片名称
     */
    @GetMapping("/{filename}")
    public void serveFile(@PathVariable String filename, HttpServletResponse resp) {
        int buffSize = 1024 * 10;
        byte[] buff = new byte[buffSize];
        try (
                BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(Paths.get(filePath + filename)), buffSize);
                BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream(), buffSize)) {
            while (bis.read(buff) != -1) {
                bos.write(buff);
                bos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String save(MultipartFile file) {
        try {
            // 将文件保存在服务器目录中
            // 文件名称
            String uuid = UUID.randomUUID().toString();
            // 得到上传文件后缀
            String originalName = file.getOriginalFilename();
            String ext = FileTool.getExtension(originalName);
            // 新生成的文件名称
            String fileName = uuid + ext;
            // 复制文件
            File targetFile = new File(filePath, fileName);
            System.out.println(targetFile);

            file.transferTo(targetFile);

            return uuid + ext;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
